package com.ws.client.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogHelper {
    public static void debug(String msg) {
        Date date = new Date(); // 获取当前时间
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); // 定义时间格式
        String currentTime = format.format(date); // 格式化时间
        String outMsg = "[" + currentTime + "]" + msg;
        System.out.println(outMsg);

        try {
            String currentDirectory = System.getProperty("user.dir");
            log(outMsg, currentDirectory + "\\logs\\log_" + (date.getMonth() + 1) + "_" + date.getDate() + ".txt");
        } catch (Exception e) {

        }
    }

    public static void log(String msg, String fileName) {
        FileWriter fw = null;
        try {
            //如果文件存在，则追加内容；如果文件不存在，则创建文件
            File f = new File(fileName);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            fw = new FileWriter(f, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(msg);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
